<template>
  <el-dialog
    :title="state.title"
    @close="handleClose"
    width="600"
    v-model="state.visible"
    :before-close="beforeClose"
    :loading="state.loading"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <div>
      <el-table :data="data" style="width: 100%">
        <el-table-column prop="dealerId" :label="t('system.agentStationDealer.dealerId')">
          <template v-slot="scope">
            <el-select v-model="scope.row.dealerId" :placeholder="t('system.agentStationDealer.placeholder.dealerId')" clearable>
              <el-option v-for="(dealer, index) in dealers" :key="index" :value="dealer.id" :label="dealer.name" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="percent" :label="t('system.agentStationDealer.percent')">
          <template v-slot="scope">
            <el-input-number
              style="width: 220px"
              :min="0.01"
              :max="1.00"
              :precision="2"
              v-model="scope.row.percent"
              :placeholder="t('system.agentStationDealer.placeholder.percent')"
            />
          </template>
        </el-table-column>

        <el-table-column width="60" prop="operate" :label="t('system.agentStationDealer.operate')">
          <template v-slot="scope">
            <div class="menu-btn">
              <el-tooltip class="box-item" effect="dark" :content="t('crud.deleteText')" placement="top">
                <el-button link type="primary" icon="delete" @click="handleDelete(scope)" />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-button class="mt-4" style="width: 100%" @click="handleAdd">添加分润成员</el-button>
    </div>

    <template #footer>
      <el-button @click="handleClose" :loading="state.form.loading">取消</el-button>
      <el-button type="primary" @click="onSave" :loading="state.form.loading">保存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {agentStationDealerList, agentStationDealerSave} from '@/api/system/agentStationDealer'
import {dealerList} from '@/api/system/dealer'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'

const { t } = useI18n()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum'))

const emits = defineEmits(['success'])

const state = reactive({
  visible: false,
  loading: false,
  form: {
    loading: false,
  },
  recharge: {},
  title: t('system.agentStation.action.bindDealer'),
  page: {
    pageSize: 9999,
    pageNum: 1,
  },
  total: 0,
  query: {},
})


const data = ref<any[]>([])

const agentStation = ref<any>({})
const dealers = ref<any[]>([])

const openDialog = (row?: any) => {
  agentStation.value = row
  state.visible = true
  getData()
}

const handleAdd = () => {
  let row = {
    index: data.value.length,
    dealerId: null,
    percent: null
  }
  console.log(row)
  data.value.push(row)
}

// 删除
const handleDelete = async (row: any) => {
  data.value = data.value.filter(item => item.index !== row.$index)
}

const handleClose = () => {
  state.visible = false
}

const beforeClose = (done: () => void) => {
  done()
}
defineExpose({
  openDialog,
})

const getDict = () => {
  dealerList({ ...state.page, ...{ status: EnableStatusEnum.value.Enabled} }).then((res) => {
    dealers.value = res.data.rows
  })
}
getDict()


const getData = () => {
  state.loading = true
  agentStationDealerList({
    ...state.page,
    ...state.query,
    ...{ agentStationId: agentStation.value.id}
  })
    .then((res) => {
      let rows = res.data.rows
      rows.forEach((row, index)=> {
        row.index = index
        row.percent = Number(row.percent)
      })
      data.value = rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

// 保存数据
const onSave = async () => {
  state.form.loading = true
  agentStationDealerSave({ agentStationId: agentStation.value.id, dealers: toRaw(data.value) }).then(()=>{
     ElMessage.success(t('operate.tooltip.success'))
     emits('success')
     handleClose()

   }).finally(()=>{
     state.form.loading = false
   })
}
</script>
